package com.gzw.dms.KJ;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.support.v4.util.ArrayMap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.gson.reflect.TypeToken;
import com.gzw.dms.R;
import com.gzw.dms.adapter.CountyAdapter;
import com.gzw.dms.adapter.MainAdapter1;
import com.gzw.dms.adapter.MoreAdapter;
import com.gzw.dms.adapter.SelectDepartAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.bean.City_Info;
import com.gzw.dms.bean.CuotomerInfo;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.TwitterRestClient;
import com.gzw.dms.utils.UrlUtils;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SelectCityActivity extends Activity {
    private DisplayMetrics dm;
    private PopupWindow popWindow;
    private MainAdapter1 mainAdapter;
    private MoreAdapter cityAdapter;
    private CountyAdapter countyAdapter;
    private Button btn_pop_submit;
    private ListView morelist;
    private ListView mainlist;
    private GridView countylist;
    private TextView tv;
    private String province_id="";
    private String city_id="";
    private List<String> county_id = new ArrayList<>();
    private String province="";
    private String city="";
    private List<String> county = new ArrayList<>();
    private String tag = "MainActivity";
    private List<City_Info> city_infos;
    private List<City_Info> county_infos;
    protected int checkNum;
    List<String> selectID = new ArrayList<String>(); //选中的ID
    private GoogleApiClient client;
    private Context mContext;
    private String who = "0";
    private Intent mIntetn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_select_city);
        dm = new DisplayMetrics();
        mIntetn=getIntent();
        // 取得窗口属性
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        tv = (TextView) findViewById(R.id.tv);
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
        mContext = this;
        who=(String)mIntetn.getExtras().get("who");
        tv.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                downPopwindow();
            }
        });    }


    public void downPopwindow() {
        // showAsDropDown(View anchor);相对某个控件的位置（正左下方），无偏移
        // showAsDropDown(View anchor, int x, int
        // y);相对某个控件的位置，有偏移;x表示相对x轴的偏移，正表示向左，负表示向右；y表示相对y轴的偏移，正是向下，负是向上；
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_down,
                null);
        int screenHeight = dm.heightPixels * 3 / 4;
        // 这里就给具体大小的数字，要不然位置不好计算
        popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT,
                screenHeight);
        // popWindow.setAnimationStyle(R.style.anim);// 淡入淡出动画
        // popWindow.setTouchable(false);// 是否响应touch事件
        popWindow.setFocusable(true);// 是否具有获取焦点的能力
        // 点击PopupWindow以外的区域，PopupWindow是否会消失。
        popWindow.setBackgroundDrawable(new BitmapDrawable());
        popWindow.setOutsideTouchable(true);

        mainlist = (ListView) contentView.findViewById(R.id.classify_mainlist);
        morelist = (ListView) contentView.findViewById(R.id.classify_morelist);
        countylist = (GridView) contentView.findViewById(R.id.gv_county);
        btn_pop_submit = (Button) contentView.findViewById(R.id.btn_pop_submit);

        mainAdapter = new MainAdapter1(this);
        mainlist.setAdapter(mainAdapter);

        mainlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                province_id = String.valueOf(position + 2);
                ShowCityTask showCityTask = new ShowCityTask();
                showCityTask.execute(province_id);
//                initAdapter(position);
                List<String> provinces = Arrays.asList(SelectCityActivity.this.getResources().getStringArray(R.array.province_item));
                province = provinces.get(position);
                mainAdapter.setSelectItem(position);
                mainAdapter.notifyDataSetChanged();
            }
        });
        mainlist.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        // 一定要设置这个属性，否则ListView不会刷新

        morelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                city_id = city_infos.get(position).getCitycode();
                ShowOrderTask showOrderTask = new ShowOrderTask();
                showOrderTask.execute();
                city = city_infos.get(position).getCityname();
                city_id = city_infos.get(position).getCitycode();
                cityAdapter.setSelectItem(position);
                cityAdapter.notifyDataSetChanged();
            }
        });

        countylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CountyAdapter.Holder holder = (CountyAdapter.Holder) view.getTag();
                holder.checkBox.toggle();
                countyAdapter.getIsSelected().put(position, holder.checkBox.isChecked());
                if (holder.checkBox.isChecked() == true) {
                    checkNum++;
                    county_id.add(String.valueOf(county_infos.get(position).getCitycode().trim()));
                    county.add(String.valueOf(holder.checkBox.getText()));
                    Log.e(tag, "onItemClick====" + "checkNum" + checkNum);
                } else {
                    checkNum--;
                    county_id.remove(String.valueOf(county_infos.get(position).getCitycode().trim()));
                    county.remove(String.valueOf(holder.checkBox.getText()));
                    Log.e(tag,"onItemClick====" + "checkNum" + checkNum);

                }
            }
        });

        btn_pop_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(tag,"onClick==" + "province=" + province + "city=" +city +
                        "county=" + county + " province_id =" + province_id + "city_id=" + city_id +
                        "county_id= " + county_id);
                String county1 = String.valueOf(county);
                String county_id1 = String.valueOf(county_id);
                Intent intent = new Intent();
                intent.putExtra("province", province);
                intent.putExtra("city", city);
                intent.putExtra("county", county1);
                intent.putExtra("province_id", province_id);
                intent.putExtra("city_id", city_id);
                intent.putExtra("county_id", county_id1);
                if (who.equals("1")){
                    setResult(4, intent);
                }else {
                    setResult(2, intent);

                }
                finish();

            }
        });
        popWindow.showAsDropDown(tv);
    }

    /**
     * 获取县城的方法并显示
     */
    public void initCountAdapter(int location) {
        city_id = city_infos.get(location).getCitycode();
        ShowOrderTask showOrderTask = new ShowOrderTask();
        showOrderTask.execute();
    }
    public class ShowOrderTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {

            Map<String, String> map = new HashMap<>();
            map.put("citye_parent_id", city_id);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetCityInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            if (result.trim() == null
                    || result.trim().length() == 0) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    county_infos = JsonUtil.getPersons(successMsg, new TypeToken<List<City_Info>>() {
                    }.getType());
                    countyAdapter = new CountyAdapter(mContext, county_infos);
                    countylist.setAdapter(countyAdapter);

                    countyAdapter.notifyDataSetChanged();
                }
            }
        }
    }
    /**
     * 获取地级市的方法并显示
     */
    public void initAdapter(int location) {
        province_id = String.valueOf(location+2);
        ShowCityTask showCityTask = new ShowCityTask();
        showCityTask.execute(province_id);
    }
    public class ShowCityTask extends AsyncTask<String , Void, String > {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {

        }

        protected String doInBackground(String... params) {
            Map<String, String> map = new HashMap<>();
            map.put("citye_parent_id", province_id);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appGetCityInfo"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {

            if (result.trim() == null
                    || result.trim().length() == 0) {
                T.showShort(mContext, "连接服务器异常");
            } else {
                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    city_infos = JsonUtil.getPersons(successMsg, new TypeToken<List<City_Info>>() {
                    }.getType());
                    cityAdapter = new MoreAdapter(mContext, city_infos);
                    morelist.setAdapter(cityAdapter);
                    cityAdapter.notifyDataSetChanged();
                }
            }
        }
    }
    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
//        client.connect();
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "Main Page", // TODO: Define a title for the content shown.
//                Uri.parse("http://host/path"),
//                Uri.parse("android-app://com.wdxtest.multiselect_city/http/host/path")
//        );
//        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();
//        Action viewAction = Action.newAction(
//                Action.TYPE_VIEW, // TODO: choose an action type.
//                "Main Page", // TODO: Define a title for the content shown.
//                Uri.parse("http://host/path"),
//                Uri.parse("android-app://com.wdxtest.multiselect_city/http/host/path")
//        );
//        AppIndex.AppIndexApi.end(client, viewAction);
//        client.disconnect();
    }
}


